package com.macrosolution.exdebito


import static org.springframework.http.HttpStatus.*

import java.lang.ProcessBuilder.Redirect;

import org.dom4j.DocumentType;

import com.sun.org.apache.xalan.internal.xsltc.compiler.Sort;

import grails.converters.JSON
import grails.plugin.springsecurity.annotation.Secured;
import grails.transaction.Transactional

/**
 * PraticaController
 * A controller class handles incoming web requests and performs actions such as redirects, rendering views and so on.
 */
//@Transactional(readOnly = true)
@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_CC','ROLE_AVV','ROLE_C','ROLE_SC','ROLE_BCKOFF'])
class PraticaController {
	def springSecurityService
	static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

	def index = {
		params.max = Math.min(max ?: 10, 100)
		respond Pratica.list(params), model:[praticaInstanceCount: Pratica.count()]
	}

	def list = {
		User secUser =springSecurityService.currentUser
		List<User> families=(List<User>)secUser.getFamily()

		Set<Pratica> pratiche = Pratica.findAllByUserInList(families,[sort: "lastUpdated", order: "desc"]);
		render view:'list', model:[pratiche:pratiche,secUser:secUser]
	}

	def show(Pratica praticaInstance) {
		respond praticaInstance
	}

	def create() {
		respond new Pratica(params)
	}

	@Transactional
	def save(Pratica praticaInstance) {
		if (praticaInstance == null) {
			notFound()
			return
		}

		if (praticaInstance.hasErrors()) {
			respond praticaInstance.errors, view:'create'
			return
		}

		praticaInstance.save flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.created.message', args: [
					message(code: 'praticaInstance.label', default: 'Pratica'),
					praticaInstance.id
				])
				redirect praticaInstance
			}
			'*' { respond praticaInstance, [status: CREATED] }
		}
	}

	def edit(Pratica praticaInstance) {
		respond praticaInstance
	}

	@Transactional
	def update(Pratica praticaInstance) {
		if (praticaInstance == null) {
			notFound()
			return
		}

		if (praticaInstance.hasErrors()) {
			respond praticaInstance.errors, view:'edit'
			return
		}

		praticaInstance.save flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.updated.message', args: [
					message(code: 'Pratica.label', default: 'Pratica'),
					praticaInstance.id
				])
				redirect praticaInstance
			}
			'*'{ respond praticaInstance, [status: OK] }
		}
	}


	//	def delete={Pratica pratica->
//		String message
				//		if(pratica){
	//			User secUser =springSecurityService.currentUser
		//
	//			//viene gestita per ora la cancellazione dell'anomalia in quanto la pratica comprende e è solo fata dall'anomalia
	//			//In seguito dovra essere gestioto anche il sovraindebitamento
	//			if(pratica.isEditableByUser(secUser)){
	//				List<String> auths =secUser.authorities*.authority
	//				if(auths.contains("ROLE_ADMIN") ||auths.contains("ROLE_AMM")){
	//					pratica.delete(flush:true)
	//				}else{
	//					User amm = secUser.getParentRole("ROLE_AMM");
	//					if(amm){
	//						pratica.user=amm
	//						pratica.save(flush:true)
	//					}
	//				}
	//					message="{'message':'Pratica cancellata con successo!'}"
	//			}else{
	//					message="{'message':'Non si possiedono i permessi per cancellare la pratica selezionata!'}"
	//			}
	//
	//		}else{
	//			message="{'message':'impossibile trovare la pratica selezionata'}"
	//
	//		}
	//		render JSON.parse(message) as JSON
	//	}
	
	@Transactional
	def delete(Pratica praticaInstance) {
		if (praticaInstance == null) {
			notFound()
			return
		}
		praticaInstance.delete flush:true
		render JSON.parse(message) as JSON
		//		request.withFormat {
		//			form {
		//				flash.message = message(code: 'default.deleted.message', args: [message(code: 'Pratica.label', default: 'Pratica'), praticaInstance.id])
		//				redirect action:"index", method:"GET"
		//			}
		//			'*'{ render status: NO_CONTENT }
		//		}
	}

	protected void notFound() {
		request.withFormat {
			form {
				flash.message = message(code: 'default.not.found.message', args: [
					message(code: 'praticaInstance.label', default: 'Pratica'),
					params.id
				])
				redirect action: "index", method: "GET"
			}
			'*'{ render status: NOT_FOUND }
		}
	}

	def anomaliabancaria(){
		Pratica praticaInstance = Pratica.findByIdentifier(params.id)
		Interview intervista = Interview.findById(praticaInstance.anomaliaBancaria.interviewId)
		User pratica_owner = praticaInstance.user
		User logUser = springSecurityService.currentUser
		def family = logUser.getFamily()

		def autorized = false
		if(family){
			for(User user:family){
				if(user.id.equals(pratica_owner.id)){
					autorized=true;
					break;
				}
			}
		}
		if(autorized){

			
			
			render view:'anomaliabancaria', model:[praticaInstance: praticaInstance]
		}else{

			
			render view :'/_errors/403'
		}



	}
	def load_file(){
		Pratica praticaInst = Pratica.findById(params.praticaId)
		AnomaliaBancaria ab = praticaInst.anomaliaBancaria
		if(ab){
			if(ab.fileDocument){
				render template:'listfile', model:[fileList: ab.fileDocument,praticaId:praticaInst.id]
			}else{

				render template:'listfile', model:[fileList: ab.fileDocument,praticaId:praticaInst.id]
			}

		}else{
			//TODO pratica non trovata redirect a dove??lista forse
			response.status=401
			render "Pratica nn trovata"
		}
	}

	def load_folder(){
		//TODO se non ci sono cartelle ??

		def user = springSecurityService.currentUser
		Pratica praticaInstance = Pratica.findById(params.praticaId)
		def folders = DocType.findAllByDocumentCategory(2)
		render template:'anomaliaFolderThree' ,model:[folders:folders,praticaInstance:praticaInstance]

	}



	def showFileDetail(){
		def fileId = params.fileId
		FileDocument fd = FileDocument.findById(fileId)

		if(fd){
			render template:'filedetailpopup', model:[fd:fd]
		}else{

			response.status=401
			render "Impossibile recuperare le inforamazioni del file,riprovare piu tardi.."

		}

	}

	def downloadFile(){
		Pratica pI = Pratica.findById(params.praticaId)
		FileDocument fd=  FileDocument.findById(params.fileId)

		if(fd){
			def filePath = fd.filePath+File.separator+fd.fileName
			//TODO settare content type on content type del file
			response.setContentType("APPLICATION/OCTET-STREAM")
			response.setHeader("Content-Disposition", "Attachment;Filename=\"${fd.fileName}\"")
			def file = new File(filePath)
			def fileInputStream = new FileInputStream(file)
			def outputStream = response.getOutputStream()
			byte[] buffer = new byte[4096];
			int len;
			while ((len = fileInputStream.read(buffer)) > 0) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush()
			outputStream.close()
			fileInputStream.close()
		}else{
			flash.message = message(code:"Non riesco a trovare il file")

			redirect(action:'anomaliabancaria',id:pI.identifier)
		}
	}

	def deleteAnomaliaFile(){
		Pratica pratica= Pratica.get(params.getLong('id_pratica'));
		AnomaliaBancaria anomaliabancaria = pratica.anomaliaBancaria
		def FileDocument fdInstance = FileDocument.findById(params.id)
		if(fdInstance){
			anomaliabancaria.removeFromFileDocument(fdInstance);
			fdInstance.delete(flush:true)
			render "File cancellato correttamente"
		}else{
			//non riesco a trovare il file
			response.status=401
			render "Non riesco a trovare il file"
		}
	}
	
	def upload_an(){
		Pratica praticaInstance =Pratica.findById(params.idPratica)
		DocType dt = DocType.findById(params.documentType.id);
		AnomaliaBancaria abInstance = praticaInstance.anomaliaBancaria
		//TODO cil percorso /upload/idpratica/nomefile
		//		new File(grailsApplication.config.uploadFolder+File.separator+"Pratica"+File.separator+"AnomaliaBancaria"+File.separator+praticaInstance.anomaliaBancaria.anomaliaBancariaType.siglaAnomaliaBancaria+File.separator+praticaInstance.identifier+File.separator )
		def folder = new File(grailsApplication.config.uploadFolder+File.separator+praticaInstance.identifier+File.separator+dt.documentType+File.separator)
		if( !folder.exists() ) {
			folder.mkdirs()
		}
		if(!(request.getFile('file'))) {
			flash.message = "Il file non deve essere vuoto"
			redirect(action:'anomaliabancaria',id:praticaInstance.identifier)
		} else {
			def file = request.getFile('file')
			def name_replace = file.originalFilename.replace(' ', '')
			List<FileDocument> listfileAnomalia = abInstance.fileDocument
			def findName = false
			listfileAnomalia.each {FileDocument ft->

				if(ft.documentType==dt && ft.fileName.equals(name_replace) ){
					

					findName=true
				}
			}


			if(!findName){

				def user = springSecurityService.currentUser
				def docInstance = new FileDocument()
				docInstance.user=user

				//replace del nome
				//			def name_replace = file.originalFilename.replace(' ', '')
				docInstance.fileName = name_replace

				docInstance.comments = params.comments
				docInstance.filePath = folder
				docInstance.file_estension= file.contentType
				docInstance.fileSize=file.size
				docInstance.documentType = dt
				file.transferTo(new File(docInstance.filePath,name_replace))
				docInstance.save(flush:true)
				abInstance.fileDocument.add(docInstance)
				abInstance.save(flush:true)
				flash.message = message(code: 'File creato correttamente',)

				redirect(action:'anomaliabancaria',id:praticaInstance.identifier)

			}else{

				flash.message = "Esiste gia un file con questo nome nella stessa cartella!"
				redirect(action:'anomaliabancaria',id:praticaInstance.identifier)

			}
		}

	}

	def uploadAj(){
		
		Pratica praticaInstance =Pratica.findById(params.piddi)
		DocType dt = DocType.findById(params.documentType);
		AnomaliaBancaria abInstance = praticaInstance.anomaliaBancaria

		def folder = new File(grailsApplication.config.uploadFolder+File.separator+praticaInstance.identifier+File.separator+dt.documentType+File.separator)
		if( !folder.exists() ) {

			folder.mkdirs()
		}

		if(!(request.getFile('file'))) {
			response.status = 401
			render "Il file non deve essere vuoto"
		} else {
			def file = request.getFile('file')
			def name_replace = file.originalFilename.replace(' ', '')
			List<FileDocument> listfileAnomalia = abInstance.fileDocument
			def findName = false
			listfileAnomalia.each {FileDocument ft->
				if(ft.documentType==dt && ft.fileName.equals(name_replace) ){
					findName=true
				}
			}
			if(!findName){

				def user = springSecurityService.currentUser
				def docInstance = new FileDocument()
				docInstance.user=user

				docInstance.fileName = name_replace

				docInstance.comments = params.comments
				docInstance.filePath = folder
				docInstance.file_estension= file.contentType
				docInstance.fileSize=file.size
				docInstance.documentType = dt
				file.transferTo(new File(docInstance.filePath,name_replace))
				docInstance.save(flush:true)
				abInstance.fileDocument.add(docInstance)
				abInstance.save(flush:true)
				render 'File creato correttamente'


			}else{

				response.status=401
				render "Esiste gia un file con questo nome nella stessa cartella!"

			}
		}
	}

	def showFilesAnomalia(){
		def user = springSecurityService.currentUser
		Pratica praticaInstance = Pratica.findById(params.pId)
		DocType dc = DocType.findByIdAndDocumentCategory(params.getLong('folderId'),2)
		List<FileDocument> fileList = new ArrayList<FileDocument>()
		praticaInstance.anomaliaBancaria.fileDocument.each {FileDocument file->
			if(file.documentType == dc){
				fileList.push(file)
			}
		}
		if(fileList){
			if(params.order_by=='name'){
				def filebyname = fileList.sort {it.fileName.toLowerCase()}
				render template:'listfile',model:[fileList:filebyname,praticaId:praticaInstance.id]
			}else{
				def filebydatec = fileList.sort {-it.dateCreated.time}
				render template:'listfile',model:[fileList:filebydatec,praticaId:praticaInstance.id]
			}
		}else{
			render template:'listfile',model:[folderType:dc,praticaId:praticaInstance.id]
		}
	}

 def anomalia_files_number(Pratica pratica){
	 int result=0;
	 DocType docType=DocType.get(params.getLong('folder_id'));
	 if(pratica.anomaliaBancaria){
		if(pratica.anomaliaBancaria.fileDocument){
			for(FileDocument file:pratica.anomaliaBancaria.fileDocument){
				if(file.documentType==docType){
					result++;
				}
			}
		} 
	 }
	 render result
 }



}
